var total = 0;
function pagerFilter(data) {
    if (typeof data.length == 'number' && typeof data.splice == 'function') {	// is array
        data = {
            total: data.length,
            rows: data
        }
    }
    var dg = $(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        showPageList: false,
        onSelectPage: function (pageNum, pageSize) {
            opts.pageNumber = pageNum;
            opts.pageSize = pageSize;
            pager.pagination('refresh', {
                pageNumber: pageNum,
                pageSize: pageSize
            });
            $("#pageNum").val(pageNum);
            dg.datagrid('loadData', data);

        }
    });
    if (!data.originalRows) {
        data.originalRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalRows.slice(start, end));
    return data;
}

function dataFilter(data) {
    if (typeof data.length == 'number' && typeof data.splice == 'function') {	// is array
        data = {
            total: total,
            rows: data
        }
    }
    var dg = $(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        showPageList: false,
        onSelectPage: function (pageNum, pageSize) {
            opts.pageNumber = pageNum;
            opts.pageSize = pageSize;
            pager.pagination('refresh', {
                pageNumber: pageNum,
                pageSize: pageSize
            });
            $("#pageNum").val(pageNum);
            goPage();
        }
    });
    return data;
}

function formatDate(date, fmt) {
    var o = {
        "M+": date.getMonth() + 1, // 月份
        "d+": date.getDate(), // 日
        "h+": date.getHours(), // 小时
        "m+": date.getMinutes(), // 分
        "s+": date.getSeconds(), // 秒
        "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
        "S": date.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

/**
 * 货币格式化
 *
 * @param number
 * @param places
 *            保留小数位数(default 2)
 * @param symbol
 *            货币符号(default '')
 * @param thousand
 *            千位分隔符(default ',')
 * @param decimal
 *            小数位分隔符(default '.')
 * @returns {string}
 */
function formatCurrency(number, places, symbol, thousand, decimal) {
    number = number || 0;
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    symbol = symbol !== undefined ? symbol : "";
    thousand = thousand || ",";
    decimal = decimal || ".";
    var negative = number < 0 ? "-" : "",
        i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
}

// 只保留数字和点号(小数点只能出现一次，并且不能出现在第一位)
function cleanNotNumber(event, obj) {
    event = window.event || event;
    // 左右键移动
    if (event.keyCode == 37 | event.keyCode == 39) {
        return;
    }
    // 只留数字和.(点)
    obj.value = obj.value.replace(/[^\d.]/g, "");
    // 第一个只能数字不能是.(点)
    obj.value = obj.value.replace(/^\./g, "");
    // .(点)只能出现一次
    obj.value = obj.value.replace(/\.{2,}/g, ".");
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
}

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//yyyy-MM-dd HH:mm:SS
function getDateTime(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hh = date.getHours();
    var mm = date.getMinutes();
    var ss = date.getSeconds();
    return year + "-" + month + "-" + day + " " + hh + ":" + mm + ":" + ss;
}

function getTime(time){
    var hh = time.getHours();
    if(hh<10){
        hh = "0"+hh;
    }
    var mm = time.getMinutes();
    if(mm<10){
        mm = "0"+mm;
    }
    var ss = time.getSeconds();
    if(ss<10){
        ss = "0"+ss;
    }
    return hh + ":" + mm + ":" + ss;
}
//EasyUI用DataGrid用日期格式化
function dateFormatter(value,row,index) {
    var date = new Date(value);
    if (value == null) {
        return null;
    } else {
        return getDateTime(date);
    }
}

function timeFormatter(value,row,index){
    var date = new Date(value);
    if(value == null){
        return null;
    }else {
        return getTime(date);
    }
}


//FX获取文件路径方法
function readFileFirefox(fileBrowser) {
    try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    }
    catch (e) {
        alert('无法访问本地文件，由于浏览器安全设置。为了克服这一点，请按照下列步骤操作：(1)在地址栏输入"about:config";(2) 右键点击并选择 New->Boolean; (3) 输入"signed.applets.codebase_principal_support" （不含引号）作为一个新的首选项的名称;(4) 点击OK并试着重新加载文件');
        return;
    }
    var fileName = fileBrowser.value; //这一步就能得到客户端完整路径。下面的是否判断的太复杂，还有下面得到ie的也很复杂。
    var file = Components.classes["@mozilla.org/file/local;1"]
        .createInstance(Components.interfaces.nsILocalFile);
    try {
        // Back slashes for windows
        file.initWithPath(fileName.replace(/\//g, "\\\\"));
    }
    catch (e) {
        if (e.result != Components.results.NS_ERROR_FILE_UNRECOGNIZED_PATH) throw e;
        alert("File '" + fileName + "' cannot be loaded: relative paths are not allowed. Please provide an absolute path to this file.");
        return;
    }
    if (file.exists() == false) {
        alert("File '" + fileName + "' not found.");
        return;
    }
    return file.path;
}
//根据不同浏览器获取路径
function getFullUploadPath(fileName) {
    //判断浏览器
    var Sys = {};
    var ua = navigator.userAgent.toLowerCase();
    var s;
    (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
        (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
            (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
                (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
                    (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
    var file_url = "";
    if (Sys.ie <= "6.0") {
        //ie5.5,ie6.0
        file_url = document.getElementById("fileName").value;
    } else if (Sys.ie >= "7.0") {
        //ie7,ie8
        var file = document.getElementById("fileName");
        file.select();
        file_url = document.selection.createRange().text;
    } else if (Sys.firefox) {
        //fx
        //file_url = document.getElementById("file").files[0].getAsDataURL();//获取的路径为FF识别的加密字符串
        file_url = readFileFirefox(document.getElementById("fileName"));
    }
    return file_url;
}

function myformatter(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);

}


function myparser(s) {
    if (!s)
        return new Date();
    var ss = (s.split('-'));
    var y = parseInt(ss[0], 10);
    var m = parseInt(ss[1], 10);
    var d = parseInt(ss[2], 10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)) {
        return new Date(y, m - 1, d);
    } else {
        return new Date();
    }
}

function playFormatter(value, row, index) {
    var index = value.lastIndexOf("\/");
    var str  = value.substring(index + 1, value.length);
    return "<a target='_blank' href='" + value + "'>"+str+"</a>";
}

function picFormatter(value, row, index) {
    if (value != "" && value != null) {
        return "<a target='_blank' href='" + value + "'><img src='" + value + "' style='width:48px;height:48px'/></a>";
    }
    else {
        return "<img src='/images/default.png' style='width:48px;height:48px'/>";
    }
}
function statusFormatter(value, row, index) {
    if (value != null) {
        return value=='1'?'启用':'<p style=\"color: red\">停用</p>';
    }else {
        return value;
    }
}
function picsFormatter(value,row,index){
    var str = "";
    if(value!=null && value!="" ) {
        var values = value.split(',');
        for (var i = 0; i < values.length; i++) {
            str += "<a target='_blank' style='height: 55px;width: 55px;'href='" + value + "'><img style='height: 55px;width: 55px;position:relative;' src='" + values[i] + "'/></a>";
        }
        return str;
    }
}

function downFormatter(value, row, index) {
    if (value != "" && value != null) {
        return "<a target='_blank' href='" + value + "'>下载</a>";
    }
    else {
        return "";
    }
}

function iconFormatter(value, row, index) {
    if (value != "" && value != null) {
        return "<img src='" + value + "' style='width:48px;height:48px'/>";
    }
    else {
        return "<img src='/images/default.png' style='width:48px;height:48px'/>";
    }
}

function imgBigFormatter(value, row, index) {
    if (value != "" && value != null) {
        return "<a target='_blank' href='" + value + "'><img src='" + value + "' style='width:100px;height:48px'/></a>";
    }
    else {
        return "<img src='/images/default.png' style='width:100px;height:48px'/>";
    }
}


function goPage() {
    $('#searchForm').submit();
}

function doSearch() {
    $("#pageNum").val(1);
    $('#searchForm').submit()
}

function uploadFile(fileId,urlId,isAdd){
    $("#"+fileId).click();
    $('#'+fileId).on('change', function () {
        uploadFileChange(fileId,urlId,isAdd);
    });
}

//上传图片
function uploadFileChange(fileId,urlId,isAdd) {
    $.messager.progress();
    $.ajaxFileUpload(
        {
            url: '../../upload/uploadFiles',
            secureuri: false,
            fileElementId: fileId,
            fileFieldName: "file",
            dataType: 'json',
            success: function (data, status) {
                $.messager.progress('close');
                if (data.error == 1) {
                    if (data.msg != '') {
                        $.messager.alert('提示', data.msg);
                    } else {
                        $.messager.alert('提示', "上传失败");
                    }
                } else {
                    if (isAdd) {
                        var url = $("#" + urlId).textbox('getValue')? ($("#" + urlId).textbox('getValue') + ',' + data.fileUrl):data.fileUrl;
                        $("#" + urlId).textbox('setValue', url);
                    } else {
                        $("#" + urlId).textbox('setValue', data.fileUrl);
                    }
                }
            },
            error: function (data, status, e) {//服务器响应失败处理函数
                $.messager.progress('close');
                $('#'+fileId).replaceWith("<input name='file' type='file' id='"+fileId+"'  style='display:none'/>");
                $('#'+fileId).on('change', function () {
                    addFileChange(fileId,urlId,isAdd);
                });
                $.messager.alert('提示', e);
            }
        }
    );
}



function loading() {
    $("<div class=\"datagrid-mask\" style='z-index: 9998'></div>").css({
        display: "block",
        width: "100%",
        height: $(window).height()
    }).appendTo("body");
    $("<div class=\"datagrid-mask-msg\" style='z-index: 9999'></div>").html("文件上传中。。。").appendTo("body").css({
        display: "block",
        left: ($(document.body).outerWidth(true) - 190) / 2,
        top: ($(window).height() - 45) / 2,


    });
}
function loadEnd() {
    $(".datagrid-mask").remove();
    $(".datagrid-mask-msg").remove();
}


//特殊字符检测函数
function isSpecialChar(s) {
    var reg = /^(([^\^\.<>%&';=?$"':#@!~\]\[{}\\/`\|])*)$/;
    if (reg.exec(s)) return true;
    else return false;
}

/**
 * 批量下载
 */
function batchDownLoad(){
    window.location.href ="batchDownload.json";
}

/**
 * 批量新增
 */
function batchAdd(){
    $('#batchAddFile').click();
    $('#batchAddFile').on('change', function () {
        if($('#batchAddFile').val()){
            var formData = new FormData($( "#batchAddForm" )[0]);
            $.ajax({
                url: "batchAdd.json",
                type: "POST",
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function () {
                    loading();
                },
                complete: function () {
                    loadEnd();
                },
                success: function (data) {
                    $.messager.alert("系统提示",data.msg,"info");
                    $('#batchAddFile').val('');
                }
            });
        }
    });
}
/**
 * 批量修改
 */
function batchUpdate(){
    $('#batchUpdateFile').click();
    $('#batchUpdateFile').on('change', function () {
        if($('#batchUpdateFile').val()){
            var formData = new FormData($( "#batchUpdateForm" )[0]);
            $.ajax({
                url: "batchUpdate.json",
                type: "POST",
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function () {
                    loading();
                },
                complete: function () {
                    loadEnd();
                },
                success: function (data) {
                    $.messager.alert("系统提示",data.msg,"info");
                    $('#batchUpdateFile').val('');
                }
            });
        }
    });
}

/**
 * 根据选择数据的ID 设置status
 * @param status
 * @param datagridId
 */
function setStatusBatch(status,datagridId) {
    if (datagridId == null) {
        datagridId = "infoDatagrid";
    }
    var rows = getRows(datagridId);
    if (rows.length < 1) {
        $.messager.alert("警告", "您未选择任何数据", "info", function () {
            return;
        });
    } else {
        var ids = new Array();
        for (var i = 0; i < rows.length; i++) {
            ids.push(rows[i].id);
        }
        $.ajax({
            url: "setStatusBatch.json",
            type: "POST",
            dataType: "json",
            data: {
                "ids": ids,
                "status": status,
            },
            success: function (data) {
                $.messager.alert("系统提示", data.msg, "info");
                queryData();
            }
        });
    }
}


/**
 * 为datagrid查询参数序列化form
 * @param form 查询用form
 * @returns {{}} like {"id":id,"name":name}
 */
function serializeObject(form){
    var o={};
    $.each(form.serializeArray(),function(index){
        if(o[this['name'] ]){
            o[this['name'] ] = o[this['name'] ] + "," + this['value'];
        }else{
            o[this['name'] ]=this['value'];
        }
    })
    return o;
}



/**
 *根据条件检索数据
 * @param datagridId 返回数据存放datagrid
 * @param qryFormID 查询参数所在form
 */
function queryData(datagridId,qryFormID){
    if(datagridId == null){
        datagridId = "infoDatagrid"
    }
    if(qryFormID == null){
        qryFormID = "formQuery";
    }
    if($("#"+qryFormID).form('validate')){
        $("#"+datagridId).datagrid("load", serializeObject($('#'+qryFormID)));
    }
}

/**
 * 删除datagrid中选择的数据
 */
function deleteInfoBatch(datagridId){
    if(datagridId == null){
        datagridId = "infoDatagrid";
    }
    var rows = getRows(datagridId);
    if(rows.length<1){
        $.messager.alert("警告", "您未选择任何数据","info",function(){
            return;
        });
    }
    var ids = new Array();
    for(var i = 0;i < rows.length; i++){
        ids.push(rows[i].id);
    }
    $.messager.confirm('提示框', '你确定要删除吗?',function(res) {
        if(res){
            $.ajax({
                url: "delete.json",
                type: "POST",
                dataType: "json",
                data: {
                    "ids": ids,
                },
                success: function (data) {
                    $.messager.alert("系统提示", data.msg, "info");
                    $("#infoDatagrid").datagrid().datagrid("uncheckAll");
                    queryData();
                }
            });
        }
    });
}

/**
 * 修改数据
 */
function updateInfo(){
    if($("#editForm").form('validate')) {
        var url = "";
        if (!$('#editId').textbox('getValue')) {
            url = "add.json";
        } else {
            url = "update.json";
        }
        $.ajax({
            url: url,
            type: "post",
            data: $("#editForm").serializeArray(),
            success: function (data) {
                $.messager.alert("系统提示", data.msg, "info", function () {
                    if ($('#hiddenId').textbox('getValue')) {
                        $('#editOrAddWin').window('close');
                    } else {
                        return;
                    }
                });
                replaceInfoById();
            },
            fail: function (data) {
                $.messager.alert("系统提示", data.msg ? data.msg : "操作失败！", "error");
            }
        });
    }
}


function replaceInfoById(targetId,datagridId){
    if(targetId == null){
        targetId = $("#hiddenId").textbox('getValue');
    }
    if(datagridId == null){
        datagridId = "infoDatagrid";
    }
    $.ajax({
        url: "qryInfoById.json",
        type: "POST",
        dataType: "json",
        data: {
            id: targetId,
        },
        success: function (data) {
            var datagrid = $('#'+datagridId).datagrid();
            var row = datagrid.datagrid('getSelected');
            if (row) {
                var rowIndex = datagrid.datagrid('getRowIndex', row);
                datagrid.datagrid('deleteRow', rowIndex);
                datagrid.datagrid('insertRow', {
                    index: rowIndex,
                    row: data
                }).datagrid('selectRow',rowIndex).datagrid('acceptChanges');
            }
        }
    });
}

/**
 * 判断是否选且只选了一行数据
 */
function isSelectOne(datagridID){
    if(datagridID == null){
        datagridID = "infoDatagrid";
    }
    var rows = getRows(datagridID);
    if(rows.length>1){
        $.messager.alert("警告", "只能选择一条数据进行修改");
        return false;
    }else if(rows.length<1){
        $.messager.alert("提示", "选择一条需要修改的数据");
        return false;
    }else{
        return true;
    }
}

function getRows(datagridID){
    if(datagridID == null){
        datagridID = "infoDatagrid";
    }
   return $('#'+datagridID).datagrid('getSelections');
}

function getRow(datagridID){
    if(datagridID =spring= null){
        datagridID = "infoDatagrid";
    }
   return $('#'+datagridID).datagrid('getSelected');
}

function clearQuery(){
    $('#formQuery').form('clear');
}

function clearEditWindow(){
    $('#editForm').form('clear');
    $('#editId').textbox('disable');
}

